define(function(require, exports, module){
	require("oa/approval/include/fileUtil.js")
	require("oa/act/main/css/comment.css");
	require("resource/js/ueditor/umeditor.config.js");
	require("resource/js/ueditor/umeditor.js");
	require("resource/js/ueditor/themes/default/css/umeditor.css");
	require("resource/js/ueditor/jquery.ueditor.js");
	require("resource/js/component/vitoBooks/vitobooks.css");
	var actcont = require("oa/act/js/actcont.js");
	var ajax = require("resource/js/component/ajax.js")
	var commonUtil = require("resource/js/component/commonUtil.js");
	
	//评论按钮事件
	function addCommentEvent(businessId){
		using("dialog", function() {
			var $commentBtn = $('#btnsWarp #actComment');
			$commentBtn[0].attentionList = [];
			$commentBtn.bind('click',function(){
				if ($(this).attr("class") != null && $(this).attr("class") != undefined && $(this).attr("class").indexOf("l-btn-disabled") >= 0) {
					return;
				}
				if(this.dlg && this.dlg.length > 0){
					//清空
					UM.getEditor('commentContent').setContent("");
					$("#commentImgName").html("");
					$("#commentAttName").html("");
					this.dlg.dialog('open');
				}else{
					using(["vitoat"], function() {
						$('.vitoat-inputoract').vitoat();
					});
					var btnObj = this;
					this.dlg = $("<div id='attCommentDialog' style='overflow:auto;'></div>").appendTo("body").dialog({
						title: "评论",
						modal:true,
						width:400,
						height:350,
						resizable:false,
						href: BASEPATH + '/view/oa/act/main/actComment',
						buttons: [{
							text: '发送',
							iconCls:'icon-ok',
							accessKey:{akey:18,mkey:83},
							handler:function(){
								if($("#commentForm").form("validate")){
									var commentContent = UM.getEditor('commentContent').getContent();
									if (commentContent == null || commentContent == "") {
										$.messager.show({ 
											 title:'',
											 msg: "评论内容不能为空！",
											 timeout:1000,
											 showType:'slide'
										 });
										return;
									}
									if (UM.getEditor('commentContent').getContentTxt().length > 800) {
										$.messager.show({
											 title:'',
											 msg: "评论内容不能超过800字符！",
											 timeout:1000,
											 showType:'slide'
										 });
										return;
									}
									var imgList = $(".img-block");
									var commentImg = [];
									for(var i = 0; i < imgList.length; i++){
										commentImg.push($(imgList[i]).data('img'));
									}
									var commentAtt = [];
									var attList = $(".att-block");
									for (var i = 0; i < attList.length; i++) {
										commentAtt.push($(attList[i]).data('att'));
									}
									var userids=$('.vitoat-inputoract').vitoat('getIds');
//									var attentionList = btnObj.attentionList.join(',').split(",");
//									$.each(userids,function(i,item){
//									　　　　if(attentionList.indexOf(item) === -1 ){
//											attentionList.push(item);
//									　　　　}
//									　　});
										
									var formData = {
										businessId: $("#busenessId").val(),
										commentContent: commentContent,
										commentImg: commentImg.join(','),
										commentAtt: commentAtt.join(','),
//										attentionList: attentionList.join(','),
										attentionList: userids.join(',')
									};
									ajax.init().success(function(code, msg, data){
										if (code == 0) {
											//刷新
											$.messager.show({
												 title:'',
												 msg: "发送成功",
												 timeout:1000,
												 showType:'slide'
											 });
											setTimeout(function() {
												window.location.reload();
											}, 500);
										}
									}).post(BASEPATH + "/oa/act/comment/saveComment.htm", formData);
								}
							}
						},{
							text:'取消',
							addClass:'l-btn-red',
							iconCls:'icon-not',
							accessKey:{akey:18,mkey:67},
							handler:function(){
								btnObj.dlg.dialog('close');
							}
						}],
						onLoad: function() {
							$('#busenessId').val(businessId);
							//点击提醒关注
//							$("#attention").unbind('click')
//							$("#attention").bind('click', function() {
//								addAttention();
//							});
							var ue = UM.getEditor('commentContent');
							using(["upload"],function(){
								$("#commentImg").upload({
									title: "图片选择",
									width:400,
									height:400,
									iconAlign:'left',
									param: {
										exts: "png,jpg,bmp,gif"
									},
									onSuccessAfter: function(files) {
										var html = "<div class='img-block' data-img='"+files[0].fileUrl+"'>"
											+"<img src="+BASEPATH+files[0].fileUrl+">"
											+"<i class='delImg fa fa-times-circle' aria-hidden='true'></i></div>"
										$("#commentImgName").append(html);
										$('.delImg').bind('click',function(){
											$(this).parent().remove();
										});
									}
								});
								$("#commentUpload").linkbutton({
									onClick:function(){
										$("#commentImg").upload("show");
									}
								});
								$("#commentAtt").upload({
									title: "附件选择",
									width:400,
									height:400,
									iconAlign:'left',
									param: {},
									onSuccessAfter: function(files) {
										var fileExt = files[0].fileExt;
										var fileIcon = getFileIcon(fileExt);
										$("#commentAttName").show();
										var html = "<div class='att-block' data-att='"+files[0].fileUrl+"'>"
											+"<span class='file-name fileStyleBg "+fileIcon+"' title="+files[0].fileName + "." + files[0].fileExt +">"+files[0].fileName + "." + files[0].fileExt +"</span>"
											+"<i class='delAtt fa fa-times-circle' aria-hidden='true'></i></div>"
										$("#commentAttName").append(html);
										$('.delAtt').bind('click',function(){
											$(this).parent().remove();
											if ($(".att-block").length == 0) {
												$("#commentAttName").hide();
											}
										});
									}
								});
								//监听@键
//										$("#commentContent").keydown(function(event) {
//											if(event.shiftKey && event.keyCode == 50) {
//												if($("#addAttentionDialog").parent().is(":hidden")|| $("#addAttentionDialog").parent().length == 0){
//													addAttention();
//												}
//											}
//										});
								//修改富文本样式
								$(".edui-btn-toolbar").hide();
								$(".edui-toolbar").hide();
								$(".edui-container").css({'box-shadow':'none'});
								$(".edui-body-container").css({'height':'150px'});
								$("#commentAttUpload").linkbutton({
									onClick:function(){
										$("#commentAtt").upload("show");
									}
								});
							});
						}
					});
				}
			});
//			//关注
//			var addAttention = function () {
//				require.async(["resource/js/component/vitoBooks/vitobooks.js"],function(){
//					if(this.dlg && this.dlg.length > 0){
//						this.dlg.vitoBooks('open');
//					}else{
//						this.dlg = $("<div id='addAttentionDialog'></div>").appendTo("body").vitoBooks({
//							title: "选择提醒关注人",
//							defaultUrl:'user',
//							nodeType : 'user',
//							checkType:'checkbox',
//							width:400,
//							height:400,
//							onSave : function(nodes){
//							    var html = "";
//							    $.each(nodes,function(i,val){
//							    	$commentBtn[0].attentionList.push(val.id);
//								    html += '<input type="button" class="attentionPerson" tabindex="-1" value="@'+val.name+'">';
//							    });
//							    UM.getEditor('commentContent').execCommand('insertHtml', html);
//							}
//						});
//					}
//				});
//			}
		});
	};
	
	function resize(){
		deal_view_base_height = $(window).innerHeight()*0.21;
		$('#dealWarp').height(deal_view_base_height);
		$('#mainView').height($(window).innerHeight()-$('#subsView').innerHeight()-25);
		$('.easyui-textbox').each(function(){
			$(this).textbox('resize',$(this).parent().innerWidth()-30);
		});
		$('.easyui-combobox,easyui-datebox,easyui-datetimebox').each(function(){
			$(this).combo('resize',$(this).parent().innerWidth()/2-30);
		});
	};
	function addFileEvent(){
		if($('.fileSet') && $('.fileSet').length > 0){
			$('.fileSet .preview').unbind('click');
			$('.fileSet .preview').bind('click',function(){
				var option = $(this).parents('.fileSet').data('options');
				var fileId = option.fileId;
				var fileExt = option.fileExt;
				var fileName = option.fileName+'.'+fileExt;
				var fileUrl = option.fileUrl;
				if(isFileCanDirectShow(fileExt.toLowerCase())){
				if(isImage(fileExt.toLowerCase())){						
					window.open (BASEPATH+fileUrl)
				}else{
					window.open (BASEPATH+"/oa/pdfViewer/web/viewer.html?file="+BASEPATH+fileUrl);
				}
			}else if(isOfficeFile(fileExt.toLowerCase())){
				commonUtil.showLoadding("加载中...");
				ajax.init().success(function(code,msg,data){
					if(code==0){
						window.open(BASEPATH+"/resource/filePreview/"+data.convertFilePath);
					}
					commonUtil.hideLoadding();
				}).error(function(){
					window.location.href = BASEPATH+fileUrl;
					commonUtil.hideLoadding();
				}).post(BASEPATH+"/oa/preview/file/previewOffice.htm",{"fileId":fileId})
			}
				
			});
			$('.fileSet .download').unbind('click');
			$('.fileSet .download').bind('click',function(){
				var option = $(this).parents('.fileSet').data('options');
				window.location.href = BASEPATH+option.fileUrl;
			});
		}
	};
	
	function getFileSize (size){
		var result = size < 1024 ? size.toFixed(2)+'B' 
   				: size < (1024*1024) ? (size/1024).toFixed(2)+'KB'
				:(size/(1024*1024)).toFixed(2)+'MB';
   		return result;
	};
	function getFileIcon(ext){
		var iconClass='';
		if(/^(gif|png|jpg|jpeg|bmp)$/i.test(ext)){
			iconClass = 'filePicture';
		}else if(/^(mp3|mp4|avi|dat|mkv|flv)$/i.test(ext)){
			iconClass = 'mediaIcon';
		}else if(/^(txt|doc|docx)$/i.test(ext)){
			iconClass = 'fileDocx';
		}else if(/^(pdf)$/i.test(ext)){
			iconClass = 'filePdf';
		}else{
			iconClass = 'fileUnknown';
		}
		return iconClass;
	};
	
	//绘制多行datagird类型数据
	function createDatagrid(data){
		var tableName = data.tab&&data.tab.tablename||'';
		var html = '<li><span>明细表单：</span>';
		html += '<a class="dataGrid link">'+tableName+'</a></li>'
		$(html).appendTo(this)
		.find('.dataGrid')
		.data('data',data)
		.click(function(){
			if(window.sessionStorage){
				var data = $(this).data('data');
				window.sessionStorage.ACT_DATAGRID_DATA=JSON.stringify(data);
				window.open(BASEPATH+'/view/oa/act/main/dataGrid');
			}else{
				alert('您的浏览器版本太低');
			}
		});
	};
	
	//绘制单行表单数据
	function initFormData(data){
		var li='';
		if(data.data.length>0){
			for(var keyval=0;keyval<data.data.length;keyval++){
				for(var k in data.cols){
					if(data.cols[k].showtype==actcont.showType.FORM_SHOWTYPE_HIDDEN){
						if(data.data[keyval] && data.data[keyval][data.cols[k].colname]){
							li+="<li><span>"+data.cols[k].colnamech+"：</span><b><span style='letter-spacing: 2px;color:#333;'><xmp>"+(data.data[keyval]?(data.data[keyval][data.cols[k].colname]||""):"")+"</xmp></span></b></li>";	
						}
					}else if(data.cols[k].showtype==actcont.showType.FORM_SHOWTYPE_FILE){
						li += "<li><span>"+data.cols[k].colnamech+"：</span>";
						var fileWarp = '';
						if(data.data[keyval] && data.data[keyval][data.cols[k].colname] && data.dataaddon){	
							var files = data.dataaddon[data.cols[k].colname];
							if(files&&files.length>0){				
								for(var i=0;i<files.length;i++){
									var file = files[i];
									var fileName = file.fileName+"."+file.fileExt;
									//var size = getFileSize(file.fileSize);
									var icon = getFileIcon(file.fileExt);
									var show = true;
									if(/^(gif|png|jpg|jpeg|bmp)$/i.test(file.fileExt)){
										show = false;
									}
									fileWarp += '<div class="fileSet" style="display: inline-block; min-height: 45px; margin-top:8px;" data-options=\''+JSON.stringify(file)+'\'>'
				   					+ '<div class="'+icon+'">'
				   						+'<span class="file-name preview link">'+fileName+'</span>'
				   						+'<span ><a class="file-action preview">预览</a><a '+(show?'':'style="display:none"')+' class="file-action download" download>下载</a></span>'
			   						+'</div></div></li>';
								}
							}
						}
						li +="<span>"+fileWarp+"</span></li>";	
						continue;
					}else if(data.cols[k].showtype==actcont.showType.FORM_SHOWTYPE_SIGN){
						var src = data.data[keyval]?(data.data[keyval][data.cols[k].colname]||null):null;
						src && (li+='<li><span>'+data.cols[k].colnamech+'：</span><span><img style="max-height: 45px;max-width: 45px;vertical-align: middle;" src="'+src+'"/></span></li>');
					}else{
						li+='<li><span>'+data.cols[k].colnamech+'：</span><span><xmp>'+(data.data[keyval]?(data.data[keyval][data.cols[k].colname]||""):"")+'</xmp></span></li>';
					}
				}
			}
		}
		this.append(li);
	};
	/**
	 * 绘制节点表单
	 */
	function paintNodeDetail(data){
		var tab;
		var $obj=this;
		if(data && data.length>0){
			var tabWarp = '<ul class="actForm"></ul>';
			$obj.append(tabWarp);
			$.each(data,function(i,form){
				tab = form.tab;
				if(tab){
					if(tab.ismore == '0'){
						createDatagrid.call($obj.children('.actForm'),form);
					}
					if(tab.ismore == '1'){
						initFormData.call($obj.children('.actForm'),form);
					}
					if(tab.hasOwnProperty("hangupuserid")){
						$('#hangUpUser').val(tab.hangupuserid||'');
					}
				}
			});
		}
	};
	
	var approce_status_icon = {'1':'','2':'approval-wait','3':'approval-ok'};
	/**
	 * 节点审批状态
	 */
	function paintNodeBase(data){
		var userName = data.username;
		var dealTime = data.dealtime;
		var action = data.action;
		//var seal = data.seal;
		var color;
		if(data.taskid){
			color ='highLight';
			this.addClass(approce_status_icon['3']);
		}else{
			approce_status_icon[data.status]&&this.addClass(approce_status_icon[data.status]);
			color = data.status == '2'?'highLight':'';
		}
		
		color && this.addClass(color);
		userName && this.append('<span>'+userName+'</span>');
		action && this.append('<span>'+action+'</span>');
		//seal && this.append('<span style="font-weight:normal;color: #777;">印章：<img style="max-height:45px;max-width:45px;vertical-align: middle;" src="'+BASEPATH+seal+'"></span>')
	};
	
	//根据节点数据绘图
	function paintNode(view,index){
		if(view){
			var nodeWarp,detailWarp,main,subs,detail;
			var id='act_'+(view.taskid||view.processnodeid)+'_'+index;
			if($('#'+id).length == 0){
				//首节点
				if(view.processnodeid == actcont.startTask){
					$('#startWarp').append(
						'<div id="'+id+'" class="node start">'
							+'<div class="node-detail start"></div>'
						+'</div>'
					);
				}else{
					$('#approvalWarp').append(
						'<div id="'+id+'" class="node">'
							+'<div class="node-base"></div>'
							+'<div class="node-detail"></div>'
						+'</div>'		
					);
					nodeWarp = $('#'+id).children('.node-base');
					paintNodeBase.call(nodeWarp,view);
				}
				main = view.main||[];
				subs = view.subs||[];
				detail= $.merge(main,subs);
				detailWarp = $('#'+id).children('.node-detail');
				paintNodeDetail.call(detailWarp,detail);
				addFileEvent();
			}
		}
	};
	
	function loadCCUsers(businessId){
		if(businessId){
			ajax.init().success(function(code,msg,datas){
				if(datas!=null&&datas.length>0){
					$('<div class="node"><div class="node-detail">'
				      +'<ul class="actForm"><li>'
				             +'<span>抄送人：</span>'
				             +'<span id="ccList"></span>'
			          +'</li></ul></div></div>').appendTo($('#ccWarp'));
					var colors = ['#229af9','#e91e63','#ffc107','#8bc34a','#3f51b5','#00bcd4'];
					var html="";
					$.each(datas,function(i,val){
					   var text = val.userName.substring(0,1);
					   var col_index = i%colors.length;
					   html = "<div class='approvers-item' style='width:55px'>" +
							   	"<div class='approvers-item-person' style='line-height:40px;width:40px;height:40px;background-color: "+colors[col_index]+"'>" +
							   		"<span class='name-first' style='font-size:13px;'>"+text+"</span>" +
								"</div>" +
								"<div class='personName' style='width:45px;'>"+val.userName+"</div>" +
							"</div>";
					   $("#ccList").append(html);
				   });
					$('#ccWarp').show();
				}
			}).post(BASEPATH+"/oa/actCC/queryCCUsers.htm",{businessId:businessId});
		}			
	};
	
	//加载评论列表
	function loadCommentList(bussId) {
		ajax.init().success(function(code,msg,data){
			if (code == 0 && data.length > 0) {
				var html = '<div id="actCommentList">';
				for (var i = 0; i < data.length; i++) {
					html += '<div class="item"><div class="item-head">'
						+'<span class="item-head-name">'+data[i].userName+'</span>'
						+'<span class="item-head-time">'+data[i].createTimeStr+'</span></div>'
						+'<div class="item-content"><div>'+data[i].commentContent+'</div>';
						if (data[i].commentImg != undefined && data[i].commentImg != "") {
							html += '<div class="commentImgNameList" style="clear: both; display: table;">';
								var imgArr = data[i].commentImg.split(",");
								for (var j = 0; j < imgArr.length; j++) {
									html += '<div class="list-img-block">'+
									'<img onclick="window.open(&quot;'+BASEPATH+imgArr[j]+'&quot;)" src="'+BASEPATH+imgArr[j]+'"></div>';
								}
							html +='</div>';
						}
						if (data[i].commentAtt != undefined && data[i].commentAtt != "") {
							html +='<div class="commentAttNameList" style="display: block;">';
							var attArr = data[i].commentAtt.split(",");
							for (var j = 0; j < attArr.length; j++) {
								html += '<div class="list-att-block" onclick="window.open(&quot;'+BASEPATH+attArr[j]+'&quot;)">';
								var fileNameList = attArr[j].split("_");
								var fileName = fileNameList[fileNameList.length - 1];
								if (attArr[j].indexOf(".doc") > 0 || attArr[j].indexOf(".txt") > 0 || attArr[j].indexOf(".docx") > 0){
									html +='<span class="file-name fileStyleBg fileDocx" title="'+fileName+'">'+fileName+'</span>';
								} else if (attArr[j].indexOf(".jpg") > 0 || attArr[j].indexOf(".png") > 0 || attArr[j].indexOf(".jpeg") > 0 || attArr[j].indexOf(".gif") > 0){
									html +='<span class="file-name fileStyleBg fileJpeg" title="'+fileName+'">'+fileName+'</span>';
								} else if (attArr[j].indexOf(".pdf") > 0 || attArr[j].indexOf(".swf") > 0 || attArr[j].indexOf(".wmv") > 0){
									html +='<span class="file-name fileStyleBg filepdf" title="'+fileName+'">'+fileName+'</span>';
								} else if (attArr[j].indexOf(".bmp") > 0){
									html +='<span class="file-name fileStyleBg filepmp" title="'+fileName+'">'+fileName+'</span>';
								} else if (attArr[j].indexOf(".excel") > 0){
									html +='<span class="file-name fileStyleBg fileexcle" title="'+fileName+'">'+fileName+'</span>';
								} else {
									html +='<span class="file-name fileStyleBg Unknown" title="'+fileName+'">'+fileName+'</span>';
								}
								
								html +='</div>';
							}
							
							html +='</div>';
						}
					html += '</div></div>';
				}
				html += '</div>';
				$("#commentWarp").html(html);
				$('#commentWarp').show();
			}
		}).post(BASEPATH+"/oa/act/comment/getCommentList.htm",{businessId:bussId});
	};

	//加载节点审批详情
	function loadNodeData(bussId,key,nodeId,taskId){
    	var result;
		if(bussId && key && nodeId && taskId){
			var options = {
					bussId:bussId,
					processKey:key,
					processNodeId:nodeId,
					taskId:taskId
					};
			ajax.init().sync().success(function(code,msg,data){
				result= data;
			}).post(BASEPATH+"/oa/act/actProgressTable/queryBussInfo.htm",options);
		}
		return result;
	};
	
	//审批意见开关触发动作
	function addSwitchEvent(){
		if($('#dealWarp').length>0){
			//父窗按钮域需隐藏
			var $parentWindow_btn = $('#operateBtn',window.parent.document);
			var deal_view_max_height = deal_view_base_height;
			$('#dealWarp_arrow').unbind('click');
			$('#dealWarp_arrow').bind('click',function(){
				deal_view_max_height = $(window).innerHeight()-$('#btnsWarp').innerHeight();
				if($(this).hasClass('arrow-up')){
					$("#dealWarp").animate({
						'height':deal_view_max_height}
						,'fast'
						,function(){
							$('#dealWarp_arrow').removeClass('arrow-up').addClass('arrow-down');
							$parentWindow_btn.hide();
						});
				}else{
					$("#dealWarp").animate({
						'height':deal_view_base_height
						}
						,'fast'
						,function(){
							$('#dealWarp_arrow').removeClass('arrow-down').addClass('arrow-up');
							$parentWindow_btn.show();
					});
				}
			});
		}
	};
	
	var deal_view_base_height = $(window).innerHeight()*0.21;
	module.exports={
		loadView : function(key,bussId){
			var options,viewData;
			ajax.init().success(function(code,msg,data){
				if(data){
					$('#startUser').val(data.startUser);
					$.each(data.view,function(i,item){
						viewData = $.extend({},item,loadNodeData(bussId,key,item.processnodeid,item.taskid));
						paintNode(viewData,i);
					});
				}
			}).post(BASEPATH+'/oa/act/activitiMain/getMobileProcessViewPage.htm',{key:key,bussId:bussId});
			loadCCUsers(bussId);
			loadCommentList(bussId);
			addSwitchEvent();
			if($('#btnsWarp #actComment').length >0){
				addCommentEvent(bussId);
			}
			$('#subsView').show();
			resize();
			$(window).resize(function(){
				resize();
			});
		},
		paintNode: function(nodeView,i){
			paintNode(nodeView,i);
		},
		paintCCUser:function(bussId){
			loadCCUsers(bussId);
		},
		paintComment:function(bussId){
			loadCommentList(bussId);
		},
		initComment : function(bussId){
			if($('#btnsWarp #actComment').length >0){
				addCommentEvent(bussId);
			}
		}
	};
});
